<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>模拟客户端</title>
  <script src="lib/protobuf.min.js" type="text/javascript"></script>
</head>
<body>
<h1>模拟客户端</h1>
<label>
  <input type="text" id="to"/>
</label>
<label>
  <input type="text" id="message"/>
</label>

<div id="prompt">

</div>

<div id="messageList">

</div>
<script>

  const from = 2
  const to = document.getElementById('to').value
  const message = document.getElementById('message').value
  let messageProtocol
  let buffer
  protobuf.load('/views/lib/MessageProto.proto', function (err, root) {
    if (err) throw err
    messageProtocol = root.lookup('protocol.MessageProtocol')
    const messageObject = {
      from: from,
      to: to,
      createTime: new Date().getTime(),
      content: message,
      type: 2
    }
    buffer = messageProtocol.encode(messageProtocol.create(messageObject)).finish()
  })

  let websocket

  function init () {
    initWebSocket()
  }

  function initWebSocket () {
    websocket = new WebSocket('ws://localhost:8192/chat')

    websocket.onopen = function (evt) {
      onOpen(evt)
    }

    websocket.onclose = function (evt) {
      onClose(evt)
    }

    websocket.onmessage = function (evt) {
      onMessage(evt)
    }

    websocket.onerror = function (evt) {
    }
  }

  function onOpen () {
    let loginMessage
    protobuf.load('/views/lib/MessageProto.proto', function (err, root) {
      if (err) throw err
      messageProtocol = root.lookup('protocol.MessageProtocol')
      const messageObject = {
        from: from,
        to: document.getElementById('to').value,
        createTime: new Date().getTime(),
        content: '登录用户：' + document.getElementById('to').value,
        type: 1
      }
      loginMessage = messageProtocol.encode(messageProtocol.create(messageObject)).finish()
    })
    if (websocket.readyState === WebSocket.OPEN) { // 如果WebSocket是打开状态
      websocket.send(loginMessage) // send()发送消息
    }
  }

  function onClose () {
  }

  function onMessage () {
  }

  function onError () {
  }

  window.addEventListener('load', init, false)
</script>
</body>
</html>
